package com.marco.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Objects;

/**
 * SpatialRelationUtils.java
 * Create on 2017/7/7
 * Copyright(c) JD Inc 2017. All Rights Reserved.
 * contact with xiaomingke1@jd.com
 * <pre>
 * Declaration：该Utils主要用于判定空间点面关系
 * </pre>
 */
public class SpatialRelationUtils {
    private static final Logger logger = LoggerFactory.getLogger(SpatialRelationUtils.class);

    /**
     * 该方法用于判定点是否在多边形内（边）
     * 算法->射线法
     *
     * @param point   点
     * @param polygon 多边形
     * @return 该点是否在多边形内或边上
     */
    public static Boolean isInnerPolygon(Point point, List<Point> polygon) throws Exception {
        Boolean isOnPolygon = false;//该点是否在多边形边上
        Integer nCross = 0;
        Integer size = polygon.size();
        for (int i = 0; i < size; i++) {
            Point p1 = polygon.get(i);
            Point p2 = polygon.get((i + 1) % size);
            if (Objects.equals(p1.getLat(), p2.getLat())) {
                continue;
            }
            if (point.getLat() < Math.min(p1.getLat(), p2.getLat()) || point.getLat() > Math.max(p1.getLat(), p2.getLat())) {
                continue;
            }
            Double crossLng = (point.getLat() - p1.getLat()) * (p2.getLng() - p1.getLng()) / (p2.getLat() - p1.getLat()) + p1.getLng();
            if (Objects.equals(crossLng, point.getLng())) {
                isOnPolygon = true;
                break;
            } else if (crossLng > point.getLng()) {
                nCross += 1;
            }
        }
        return isOnPolygon || (nCross % 2 == 1);
    }
}
